package com.sk.weichat.ui.message.multi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.roamer.slidelistview.SlideBaseAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.MucRoom;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.broadcast.MucgroupUpdateUtil;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.groupchat.RoomChangeContentActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewHolder;
import com.sk.weichat.view.PullToRefreshSlideListView;
import com.sk.weichat.view.TipDialog;
import com.sk.weichat.view.VerifyDialog;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.CHANGE_RESULT;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.NICKNAME;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.NOTICE;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.USERNAME;

/**
 * 群公告列表
 */
public class NoticeListActivity extends BaseActivity {

    private RecyclerView mListView;
    private TextView empty;
    private NoticeAdapter mNoticeAdapter;
    private List<MucRoom.Notice> mNoticeList = new ArrayList<>();
    private int mRole;
    private String mRoomId;

    private boolean isNeedUpdate;// 回到群组信息界面是否需要刷新ui

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_list);

        mRole = getIntent().getIntExtra("mRole", 3);
        mRoomId = getIntent().getStringExtra("mRoomId");
        initActionBar();
        initView();
        loadData();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("isNeedUpdate", isNeedUpdate);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("isNeedUpdate", isNeedUpdate);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        TextView mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        mTvTitle.setText(R.string.group_bulletin);
        ImageView mImgTitleRight = findViewById(R.id.iv_title_right);
        mImgTitleRight.setVisibility(View.VISIBLE);
        mImgTitleRight.setImageResource(R.mipmap.icon_edit_black);
        mImgTitleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mRole == 1 || mRole == 2) {
                    Intent intent = new Intent(NoticeListActivity.this, RoomChangeContentActivity.class);
                    intent.putExtra("mRole", mRole);
                    intent.putExtra("mRoomId",mRoomId);
                    intent.putExtra("change_type",NOTICE);
                    intent.putExtra("content", "");
                    startActivityForResult(intent, CHANGE_RESULT);
                } else {
                    ToastUtil.showToast(NoticeListActivity.this, R.string.tip_cannot_public_bulletin);
                }
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CHANGE_RESULT && data != null) {// 添加公告内容返回
            String text = data.getStringExtra("content");
            int change_type = data.getIntExtra("change_type", 0);
            if (change_type == NOTICE) {//修改群名称返回
                if (TextUtils.isEmpty(text)) {
                    ToastUtil.showToast(mContext, "请不要发布没有内容的公告");
                } else {
                    updateNotice(text);
                }
            }
        }
    }

    private void initView() {
        empty = findViewById(R.id.empty);
        mListView =  findViewById(R.id.pull_refresh_list);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mNoticeAdapter = new NoticeAdapter(mNoticeList);
        mListView.setAdapter(mNoticeAdapter);

    }

    private void loadData(){
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("pageSize", Constants.MUC_MEMBER_PAGE_SIZE);

        HttpUtils.get().url(coreManager.getConfig().ROOM_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<MucRoom>(MucRoom.class) {
                             @Override
                             public void onResponse(ObjectResult<MucRoom> result) {
                                 if (result.getResultCode() == 1 && result.getData() != null) {
                                     List<MucRoom.Notice> datas = result.getData().getNotices();
                                     if (mNoticeList.size()>0){
                                         mNoticeList.clear();
                                     }
                                     if (datas.size() == 0) {
                                         mListView.setVisibility(View.GONE);
                                         empty.setVisibility(View.VISIBLE);
                                     }else {
                                         mListView.setVisibility(View.VISIBLE);
                                         empty.setVisibility(View.GONE);
                                         mNoticeList.addAll(datas);
                                     }
                                     mNoticeAdapter.notifyDataSetChanged();

                                 } else {
                                     ToastUtil.showErrorData(NoticeListActivity.this);
                                 }
                             }

                             @Override
                             public void onError(Call call, Exception e) {
                                 ToastUtil.showErrorNet(NoticeListActivity.this);
                             }
                         }
                );
    }

    private void updateNotice(final String text) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("notice", text);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_UPDATE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {
                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            ToastUtil.showToast(NoticeListActivity.this,"发布成功");

                            /*刷新 重新请求公告列表数据*/
                            loadData();
                            // 更新群管理界面
                            MucgroupUpdateUtil.broadcastUpdatGroupInfoeUi(NoticeListActivity.this);

                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    private void deleteNotice(final MucRoom.Notice notice) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("noticeId", notice.getId());
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HttpUtils.get().url(coreManager.getConfig().ROOM_DELETE_NOTICE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {
                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            ToastUtil.showToast(NoticeListActivity.this,"删除成功");

                            /*刷新 重新请求公告列表数据*/
                            loadData();
                            // 更新群管理界面
                            MucgroupUpdateUtil.broadcastUpdatGroupInfoeUi(NoticeListActivity.this);
                        }
                    }
                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    class NoticeAdapter extends BaseQuickAdapter<MucRoom.Notice, BaseViewHolder> {

        public NoticeAdapter(@Nullable List<MucRoom.Notice> data) {
            super(R.layout.row_notice, data);
        }
        @Override
        protected void convert(BaseViewHolder helper, MucRoom.Notice mNotice) {
            ImageView mAvatar = helper.getView(R.id.avatar_iv);
            TextView mName = helper.getView(R.id.name_tv);
            TextView mTime = helper.getView(R.id.time_tv);
            TextView mContent = helper.getView(R.id.content_tv);
            LinearLayout mDeleteStyle1 = helper.getView(R.id.item_delete_style1);
            AvatarHelper.getInstance().displayAvatar(mNotice.getUserId(), mAvatar);
            mName.setText(mNotice.getNickname());
            mTime.setText(TimeUtils.getFriendlyTimeDesc(NoticeListActivity.this, mNotice.getTime()));
            mContent.setText(mNotice.getText());
            mDeleteStyle1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mRole == 1 || mRole == 2) {
                        deleteNotice(mNotice);
                    } else {
                        TipDialog tipDialog = new TipDialog(NoticeListActivity.this);
                        tipDialog.setTip(getString(R.string.tip_cannot_remove_bulletin));
                        tipDialog.show();
                    }
                }
            });
        }
    }
}
